package com.centling.smartSealForPhone.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.centling.smartSealForPhone.BuildConfig;
import com.centling.smartSealForPhone.R;
import com.centling.smartSealForPhone.bean.VersionBean;
import com.centling.smartSealForPhone.constants.UrlConstants;
import com.centling.smartSealForPhone.utils.FileUtil;
import com.centling.smartSealForPhone.utils.OkHttpUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Locale;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

/**
 * @author centling
 */
public class VersionDialog extends BaseDialog {

	private TextView mTvTitle;
	private LinearLayout mLayoutForceUpdate;
	private TextView mTvVersionContent;
	private Button mBtnCancel;
	private Button mBtnUpdate;
	private LinearLayout mLayoutProgress;
	private NumberProgressBar mPbBar;
	private boolean mIsDownloading = false;
	private boolean mIsForceUpdate = true;
	private boolean mIsCancled = false;
	private static final String DOWNLOAD_APK_PATH = Environment
			.getExternalStorageDirectory().getPath()
			+ "/com.centling.seal.phone/download/apk/";

	public VersionDialog(Context context, final VersionBean version, final String appVersion) {
		super(context);
		setCancelable(false);
		setCanceledOnTouchOutside(false);
        View v = View.inflate(context, R.layout.dialog_version, null);
        setContentView(v);
		setTitle("发现新版本");
		mTvTitle = findViewById(R.id.dialog_version_tv_title);
		mLayoutForceUpdate = findViewById(R.id.dialog_version_layout_forceupdate);
		mLayoutForceUpdate.setVisibility(mIsForceUpdate ? View.VISIBLE
				: View.GONE);
		mTvVersionContent = findViewById(R.id.dialog_version_tv_content);
		mBtnCancel = findViewById(R.id.dialog_version_btn_cancel);
		mBtnUpdate = findViewById(R.id.dialog_version_btn_update);
		mLayoutProgress = findViewById(R.id.dialog_version_layout_progress);
		mLayoutProgress.setVisibility(View.INVISIBLE);
		mPbBar = findViewById(R.id.dialog_progress_pb_progressbar);
		mPbBar.setProgressTextVisibility(NumberProgressBar.ProgressTextVisibility.Invisible);
		mTvTitle.setText(String.format(Locale.CHINA, "当前版本号:%s\n更新版本号:%s", appVersion,
				version.getSoftwareVersion()));
		String content = version.getVersionDescribe();
		content = TextUtils.isEmpty(content) ? content : content.replace("|",
				"\n");
		mTvVersionContent.setText(content);
		mBtnCancel.setText(mIsForceUpdate ? "退出" : "取消");
		mBtnCancel.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mIsDownloading) {
                    final String name = "sealphone_" + version.getSoftwareVersion().replace(".",
                            "_") + ".apk";
                    FileUtil.deleteFile(DOWNLOAD_APK_PATH + name);
                }
				if (mIsForceUpdate) {
					System.exit(0);
				} else {
					mIsCancled = true;
				}
				dismiss();
			}
		});
		mBtnUpdate.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				mBtnUpdate.setEnabled(false);
				mBtnUpdate.setText("更新中");
				mLayoutProgress.setVisibility(View.VISIBLE);
				mPbBar.setProgressTextVisibility(NumberProgressBar.ProgressTextVisibility.Visible);
				mPbBar.setProgress(0);
				final String path = DOWNLOAD_APK_PATH;
                final String name = "sealphone_" + version.getSoftwareVersion().replace(".",
                        "_") + ".apk";
                final File file = new File(path + name);
				if (file.exists()) {
					if (same(path + name, version.getSoftwareVersion() + "")) {
						openApkFile(getContext(), file);
						mBtnUpdate.setEnabled(true);
						mBtnUpdate.setText("更新");
						mLayoutProgress.setVisibility(View.INVISIBLE);
						return;
					} else {
						FileUtil.deleteFile(path + name);
					}
				}
				new Thread(new Runnable() {

					@Override
					public void run() {
                        mIsDownloading = true;
                        boolean result = downloadFile(getContext(), (!TextUtils
                                .equals(BuildConfig.FLAVOR,
                                        "publicCloud") ? UrlConstants.ROOTURL : "") + version
                                .getDownloadUrl(), path, name, mHandler);
                        if (result) {
                            Message msg = mHandler.obtainMessage(1, file);
							msg.sendToTarget();
						} else {
							Message msg = mHandler
									.obtainMessage(2, path + name);
							msg.sendToTarget();
						}
					}
				}).start();
			}
		});
	}

	private static void openApkFile(Context context, File file) {
		if (!checkFileEndings(file)) {
			return;
		}
		Intent it = new Intent();
		it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		it.setAction(android.content.Intent.ACTION_VIEW);
		Uri fileUri;
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
			fileUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".FileProvider", file);
		} else {
			fileUri = Uri.fromFile(file);
		}
		it.setDataAndType(fileUri, "application/vnd.android.package-archive");
		context.startActivity(it);
	}

	/**
	 * 检查文件后缀
	 */
	private static boolean checkFileEndings(File file) {
        return !(file == null || !file.exists()) && file.getPath()
                .toLowerCase().endsWith(".apk");
    }

	private boolean same(String path, String version) {
		PackageManager packageManager = getContext().getPackageManager();
		PackageInfo packageInfo = packageManager.getPackageArchiveInfo(path,
				PackageManager.GET_ACTIVITIES);
		return packageInfo != null && version.equals(packageInfo.versionName);
	}

	private boolean downloadFile(Context context, String url, String filePath,
								 String fileName, Handler handler) {
		if (TextUtils.isEmpty(url) || !FileUtil.isSDCardExist()
				|| !FileUtil.isHasSDCardPermission(context)
				|| TextUtils.isEmpty(filePath) || TextUtils.isEmpty(fileName)) {
			return false;
		}
		HttpURLConnection conn = null;
		try {
            URL u = new URL(url);
            boolean isHttps = url.startsWith("https");
            if (isHttps) {
                conn = (HttpsURLConnection) u.openConnection();
                ((HttpsURLConnection) conn).setSSLSocketFactory(
                        OkHttpUtil.createSSLSocketFactory());
                ((HttpsURLConnection) conn).setHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        // now all
                        return true;
                    }
                });
            } else {
                conn = (HttpURLConnection) u.openConnection();
            }
			conn.setConnectTimeout(10000);
			conn.setReadTimeout(20000);
			conn.connect();
			int length = conn.getContentLength();
			InputStream is = conn.getInputStream();
			File downloadFile = new File(FileUtil.createDirFile(context,
					filePath), fileName);
			if (downloadFile.exists()) {
				downloadFile.delete();
			}
			FileOutputStream fos = new FileOutputStream(downloadFile);
			int count = 0;
			int progress = 0;
			byte buf[] = new byte[1024];
			while (!mIsCancled) {
				int numread = is.read(buf);
				if (numread <= 0) {
					return true;
				}
				count += numread;
				int curProgress = (int) (((float) count / length) * 100);
				fos.write(buf, 0, numread);
				if (handler != null) {
					if (curProgress > progress) {
						progress = curProgress;
						Message msg = handler.obtainMessage(0, progress);
						handler.sendMessage(msg);
					}
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
		return false;
	}

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    int progress = (Integer) msg.obj;
                    mPbBar.setProgress(progress);
                    break;

                case 1:
                    mIsDownloading = false;
                    openApkFile(getContext(), (File) msg.obj);
                    mBtnUpdate.setEnabled(true);
                    mBtnUpdate.setText("更新");
                    mLayoutProgress.setVisibility(View.INVISIBLE);
                    break;

                case 2:
                    mIsDownloading = false;
                    if (mIsCancled) {
                        return;
                    }
                    FileUtil.deleteFile(msg.obj.toString());
                    Toast.makeText(getContext(), "更新失败", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }

    };
}
